#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#include <vector>

class Solution {
public:

    bool checkTwoElements(int left, int right, vector<int>& v)
    {
        vector<int> tmp(v.begin() + left, v.begin() + right);
        unordered_map<int, int> hash;
        for (auto e : tmp)
        {
            hash[e]++;
        }
        if (hash.size() > 2)
            return false;
        else
            return true;
    }

    int totalFruit(vector<int>& fruits) {
        int left = 0;
        int right = 0;
        int result = 0;
        int bestResult = 0;
        unordered_map<int, int> hash;
        while (right < fruits.size())
        {
            hash[fruits[right]]++;
            right++;
            result++;
            // while(!checkTwoElements(left, right, fruits))
            // {
            //     left++;
            //     result--;
            // }
            while (hash.size() > 2)
            {
                auto it = hash.find(fruits[left]);
                it->second--;
                if (it->second == 0)
                    hash.erase(it);
                left++;
                result--;
            }
            bestResult = bestResult > result ? bestResult : result;
        }
        return bestResult;
    }
};